const { createApp, ref, reactive, onMounted } = Vue;

const app = createApp({
    setup() {
        // 响应式数据
        const documents = ref([]);
        const sessions = ref([]);
        const questions = ref([]);
        const currentSession = ref(null);
        const currentQuestion = ref(null);
        const currentQuestionIndex = ref(0);
        const currentAnswer = ref('');
        const showEvaluation = ref(false);
        const evaluation = ref({});
        const showResults = ref(false);
        const results = ref({});
        const showCreateSession = ref(false);
        const newSession = reactive({
            session_name: '',
            document_ids: []
        });

        // API配置
        const API_BASE = 'http://localhost:8000/api/interview';
        const uploadUrl = `${API_BASE}/documents/upload/`;
        const uploadHeaders = {
            'X-CSRFToken': getCookie('csrftoken')
        };

        // 获取CSRF Token
        function getCookie(name) {
            let cookieValue = null;
            if (document.cookie && document.cookie !== '') {
                const cookies = document.cookie.split(';');
                for (let i = 0; i < cookies.length; i++) {
                    const cookie = cookies[i].trim();
                    if (cookie.substring(0, name.length + 1) === (name + '=')) {
                        cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                        break;
                    }
                }
            }
            return cookieValue;
        }

        // 格式化日期
        function formatDate(dateString) {
            const date = new Date(dateString);
            return date.toLocaleString('zh-CN');
        }

        // 获取状态类型
        function getStatusType(status) {
            const types = {
                'active': 'primary',
                'completed': 'success',
                'paused': 'warning'
            };
            return types[status] || 'info';
        }

        // 获取状态文本
        function getStatusText(status) {
            const texts = {
                'active': '进行中',
                'completed': '已完成',
                'paused': '暂停'
            };
            return texts[status] || status;
        }

        // 加载文档列表
        async function loadDocuments() {
            try {
                const response = await axios.get(`${API_BASE}/documents/`);
                if (response.data.success) {
                    documents.value = response.data.documents;
                }
            } catch (error) {
                console.error('加载文档失败:', error);
                ElMessage.error('加载文档失败');
            }
        }

        // 加载会话列表
        async function loadSessions() {
            try {
                const response = await axios.get(`${API_BASE}/sessions/`);
                if (response.data.success) {
                    sessions.value = response.data.sessions;
                }
            } catch (error) {
                console.error('加载会话失败:', error);
                ElMessage.error('加载会话失败');
            }
        }

        // 文件上传成功处理
        function handleUploadSuccess(response, file) {
            if (response.success) {
                ElMessage.success('文档上传成功');
                loadDocuments();
            } else {
                ElMessage.error(response.message || '上传失败');
            }
        }

        // 文件上传失败处理
        function handleUploadError(error) {
            console.error('上传失败:', error);
            ElMessage.error('文件上传失败');
        }

        // 上传前验证
        function beforeUpload(file) {
            const allowedTypes = ['text/plain', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'];
            if (!allowedTypes.includes(file.type)) {
                ElMessage.error('只支持 .txt 和 .docx 格式文件');
                return false;
            }
            return true;
        }

        // 删除文档
        async function deleteDocument(documentId) {
            try {
                await ElMessageBox.confirm('确定要删除这个文档吗？', '确认删除', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                });

                const response = await axios.delete(`${API_BASE}/documents/${documentId}/delete/`);
                if (response.data.success) {
                    ElMessage.success('文档删除成功');
                    loadDocuments();
                }
            } catch (error) {
                if (error !== 'cancel') {
                    console.error('删除文档失败:', error);
                    ElMessage.error('删除文档失败');
                }
            }
        }

        // 创建会话
        async function createSession() {
            if (!newSession.session_name.trim()) {
                ElMessage.warning('请输入会话名称');
                return;
            }

            try {
                const response = await axios.post(`${API_BASE}/sessions/create/`, {
                    session_name: newSession.session_name,
                    document_ids: newSession.document_ids
                });

                if (response.data.success) {
                    ElMessage.success('会话创建成功');
                    showCreateSession.value = false;
                    newSession.session_name = '';
                    newSession.document_ids = [];
                    loadSessions();
                }
            } catch (error) {
                console.error('创建会话失败:', error);
                ElMessage.error('创建会话失败');
            }
        }

        // 开始面试
        async function startInterview(session) {
            try {
                const response = await axios.get(`${API_BASE}/sessions/${session.id}/questions/`);
                if (response.data.success) {
                    questions.value = response.data.questions;
                    currentSession.value = session;
                    currentQuestionIndex.value = 0;
                    currentQuestion.value = questions.value[0];
                    currentAnswer.value = '';
                    showEvaluation.value = false;
                    showResults.value = false;
                }
            } catch (error) {
                console.error('开始面试失败:', error);
                ElMessage.error('开始面试失败');
            }
        }

        // 查看结果
        async function viewResults(session) {
            try {
                const response = await axios.get(`${API_BASE}/sessions/${session.id}/results/`);
                if (response.data.success) {
                    results.value = response.data;
                    showResults.value = true;
                    currentSession.value = null;
                }
            } catch (error) {
                console.error('获取结果失败:', error);
                ElMessage.error('获取结果失败');
            }
        }

        // 提交答案
        async function submitAnswer() {
            if (!currentAnswer.value.trim()) {
                ElMessage.warning('请输入答案');
                return;
            }

            try {
                const response = await axios.post(`${API_BASE}/submit-answer/`, {
                    question_id: currentQuestion.value.id,
                    answer_text: currentAnswer.value
                });

                if (response.data.success) {
                    evaluation.value = response.data.evaluation;
                    showEvaluation.value = true;
                }
            } catch (error) {
                console.error('提交答案失败:', error);
                ElMessage.error('提交答案失败');
            }
        }

        // 下一题
        function nextQuestion() {
            if (currentQuestionIndex.value + 1 >= questions.value.length) {
                // 面试完成，获取结果
                viewResults(currentSession.value);
            } else {
                currentQuestionIndex.value++;
                currentQuestion.value = questions.value[currentQuestionIndex.value];
                currentAnswer.value = '';
                showEvaluation.value = false;
            }
        }

        // 返回会话列表
        function backToSessions() {
            showResults.value = false;
            currentSession.value = null;
            currentQuestion.value = null;
            currentAnswer.value = '';
            showEvaluation.value = false;
        }

        // 组件挂载时加载数据
        onMounted(() => {
            loadDocuments();
            loadSessions();
        });

        return {
            // 数据
            documents,
            sessions,
            questions,
            currentSession,
            currentQuestion,
            currentQuestionIndex,
            currentAnswer,
            showEvaluation,
            evaluation,
            showResults,
            results,
            showCreateSession,
            newSession,
            uploadUrl,
            uploadHeaders,

            // 方法
            formatDate,
            getStatusType,
            getStatusText,
            handleUploadSuccess,
            handleUploadError,
            beforeUpload,
            deleteDocument,
            createSession,
            startInterview,
            viewResults,
            submitAnswer,
            nextQuestion,
            backToSessions
        };
    }
});

// 使用Element Plus
app.use(ElementPlus);

// 挂载应用
app.mount('#app');



